package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import common.Result;
import dao.UserDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2024-04-20
 * Time: 11:27
 */
@WebServlet("/delete")
public class DeleteServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = new Result();
        // 1.从请求中获取用户名和密码
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("userId");
        if (username == null || username.equals("")) {
            result.setCode(5001);
            result.setMessage("缺少用户 Id！");
            String respString = objectMapper.writeValueAsString(result);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respString);
            return;
        }
        // 2.读取数据库，检查用户名是否存在
        UserDao userDao = new UserDao();
        User user = userDao.selectUserByName(username);
        if (user == null) {
            // 用户不存在
            result.setCode(5002);
            result.setMessage("用户 Id 错误！");
            String respString = objectMapper.writeValueAsString(result);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respString);
            return;
        }
        // 3.执行删除逻辑
        int row = userDao.deleteUserByName(username);
        if (row != 1) {
            result.setCode(5003);
            result.setMessage("删除失败，服务器内部错误!");
            String respString = objectMapper.writeValueAsString(result);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respString);
            return;
        }
        // 4. 返回成功响应
        result.setCode(2000);
        result.setMessage("删除成功！");
        String respString = objectMapper.writeValueAsString(result);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(respString);
    }
}
